﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class LossForm : Form
    {
        public LossForm()
        {
            InitializeComponent();
        }
        tb_loss loss;
        bool insert = false;
        const string catMeasure = "Dimension";
        int dimID = 0;

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            tbLossName.Enabled = tbLossNameUzb.Enabled = cbDimension.Enabled = insert = true;
            buttonOK.Text = "Добавить";
            buttonCancel.Text = "No";
            loss = null;
        }

        private void tsbEdit_Click(object sender, EventArgs e)
        {
            if (dgvLosses.RowCount > 0 && dgvLosses.CurrentRow != null)
            {
                insert = false;
                tbLossName.Enabled = tbLossNameUzb.Enabled = cbDimension.Enabled = true;
                int lID = (int)dgvLosses["ID", dgvLosses.CurrentRow.Index].Value;
                loss = DBClass.Losses.Where(wh => wh.ID == lID).SingleOrDefault();
                if (loss != null)
                {
                    tbLossName.Text = loss.Name;
                    tbLossNameUzb.Text = loss.NameUz;
                }
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            if (dgvLosses.RowCount > 0 && dgvLosses.CurrentRow != null)
            {
                int lID = (int)dgvLosses["ID", dgvLosses.CurrentRow.Index].Value;
                loss = DBClass.Losses.Where(wh => wh.ID == lID).SingleOrDefault();

                string cName = InformationClass.Lang ? loss.Name : loss.NameUz;
                string msg = InformationClass.Lang ? "Вы действительно хотите удалить вид затрат \"" + cName + " \"" : "Сиз ҳақиқатдан ҳам ҳаражатлар турини олиб ташламоқчисиз \"" + cName + " \"";

                if (MessageBox.Show(msg, msgClass.msgAchtung, MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    DBClass.Losses.DeleteOnSubmit(loss);
                    DBClass.RESPContext.SubmitChanges();
                    ShowLosses();
                }
                else
                {
                    loss = null;
                }

            }
        }

        private void LossForm_Load(object sender, EventArgs e)
        {
            cbDimension.SelectedIndexChanged -= cbDimension_SelectedIndexChanged;
            cbDimension.DataSource = UtilClass.FillCBCategory(catMeasure);
            cbDimension.DisplayMember = "Name";
            cbDimension.ValueMember = "ID";
            cbDimension.SelectedIndex = -1;
            cbDimension.Text = string.Empty;
            cbDimension.SelectedIndexChanged += new EventHandler(cbDimension_SelectedIndexChanged);

            ShowLosses();
        }

        private void cbDimension_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbDimension.SelectedIndex >= 0)
                dimID = Convert.ToInt32(cbDimension.SelectedValue);
            else
                dimID = 0;
        }

        private void dgvLosses_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dgvLosses.Columns.IndexOf(dgvLosses.Columns["Measure"]))
            {
                if (e.Value == null)
                    return;
                else
                {
                    if ((int)e.Value == 0)
                        e.Value = "NO DATA";
                    else
                        e.Value = UtilClass.GetCategoryDisplayName((int)e.Value, catMeasure);
                }
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (insert && loss == null)
            {
                if (String.IsNullOrEmpty(tbLossName.Text) || String.IsNullOrEmpty(tbLossNameUzb.Text) || dimID == 0)
                {
                    if (InformationClass.Lang)
                        MessageBox.Show("Обязательно заполнить оба названия затрат и выбрать измерение!");
                    else
                        MessageBox.Show("Ҳаражатларнинг икки номини тўлдириш ва ўлчовни танлаш шарт! ");
                    return;
                }

                loss = new tb_loss
                {
                    Name = tbLossName.Text,
                    NameUz = tbLossNameUzb.Text,
                    Measure = dimID
                };
                DBClass.Losses.InsertOnSubmit(loss);

                tbLossName.Text = tbLossNameUzb.Text = string.Empty;


            }
            else
            {
                if (loss != null)
                {
                    loss.Name = tbLossName.Text;
                    loss.NameUz = tbLossNameUzb.Text;
                    loss.Measure = dimID;
                }

                this.Close();
            }

            try
            {
                if (DBClass.RESPContext.GetChangeSet().Deletes.Count > 0 || DBClass.RESPContext.GetChangeSet().Inserts.Count > 0 || DBClass.RESPContext.GetChangeSet().Updates.Count > 0)
                {
                    DBClass.RESPContext.SubmitChanges();
                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                }
                ShowLosses();
                tbLossName.Enabled = tbLossNameUzb.Enabled = cbDimension.Enabled = insert = false;
                buttonOK.Text = "OK";
                buttonCancel.Text = "Cancel";
            }
            catch
            {
                MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
            }


        }

        private void ShowLosses()
        {
            dgvLosses.DataSource = DBClass.Losses
                .Select(se => new
                {
                    ID = se.ID,
                    Name = se.Name,
                    NameUz = se.NameUz,
                    Measure = se.Measure
                }).Distinct().ToArray();

            dgvLosses.Columns["ID"].Visible = false;
            dgvLosses.Columns["Name"].HeaderText = "Русское название";
            dgvLosses.Columns["NameUz"].HeaderText = "Узбекское название";
            dgvLosses.Columns["Measure"].HeaderText = "Размерность";
            dgvLosses.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvLosses.AutoResizeColumns();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
    }
}
